<template>
  <el-row>
    <el-col :span="24" style="padding: 24px;">
      <el-button @click="openDialog(false)" icon="Plus" type="primary">新建账户类型</el-button>
      <el-button icon="Refresh" @click="refreshList">刷新列表</el-button>
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="24" style="padding:12px; min-height: 400px; height: 70vh;">
      <!-- 设置表格最大高度，超出出现滚动条 宽度自适应父容器-->
      <el-table v-loading="loading" :data="accountTypeList" style="width: 70%; min-width: 600px;  height: 100%;">
        <el-table-column label="名称" align="center" prop="name"></el-table-column>
        <el-table-column label="编码" align="center" prop="code"></el-table-column>        
        <el-table-column label="操作" width="300" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-link :underline="false" style="margin-left: 24px;" type="primary"
              @click="openDialog(true, scope.row)">编辑</el-link>
            <el-link :underline="false" style="margin-left: 24px;" type="primary"
              @click="action(scope.row, 'del')">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>

  <div style="width: 50%; min-width: 400px; margin: 0 auto; padding: 0;">
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>

  <!-- 新建/编辑账户类型弹窗 -->
  <el-dialog v-model="dialogVisible" :title="isEdit ? '账户类型编辑' : '新建账户类型'" width="500" draggable align-center
    :before-close="handleCloseDialog">
    <div>
      <el-form ref="accountTypeFormRef" label-suffix=":" :model="formData" :rules="formRules" label-width="120px"
        style="max-width: 600px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="formData.code"  />
        </el-form-item>
        
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="submitForm" type="primary" :loading="submitLoading">
          提交
        </el-button>
        <el-button @click="handleCloseDialog" :disabled="submitLoading">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FundUiAction } from '../../public/engine/uiAction/fundUiAction'
import { Definition } from '../../public/engine/common/definition'
import { DataPage } from '../../public/network/communicationConverter'
import { Engine } from '../../public/engine/engine.js'
import {deleteSelfAccountTypeNetworkCacheData} from '../../public/network/api'

export default {
  name: 'selfDefFundAccountType',
  data() {
    return {
      total: 0,
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: Definition.gDefualPageSize,
      },
      accountTypeList: [],
      dialogVisible: false,
      isEdit: false,
      submitLoading: false,
      accountTypeFormRef: null,
      formData: {
        id: '',
        name: '',
        code: ''
      },
      formRules: {
        code: [
          { required: true, message: '请输入编码', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      fundUiAction: new FundUiAction(),
    }
  },
  methods: {

    refreshList(){
        deleteSelfAccountTypeNetworkCacheData();
        this.getList();
    },
    async getList() {
      try {
        this.loading = true
        const res = await this.fundUiAction.getSelfFundAccountTypeData({
          pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize)
        })

        if (res && res.data && res.data.dataList) {
          this.accountTypeList = res.data.dataList
          this.total = res.data.pageInfo.total;
        } else if (res.resErr) {
          console.error('获取列表失败', res.resErr)
          ElMessage.error('获取列表失败')
        }
      } catch (error) {
        console.error('获取列表失败', error)
        ElMessage.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },
    openDialog(editMode = false, rowData = null) {
      this.isEdit = editMode
      if (editMode && rowData) {
        Object.assign(this.formData, {
          id: rowData.id,
          name: rowData.name,
          code: rowData.code
        })
      } else {
        this.resetForm()
      }
      this.dialogVisible = true
    },
    resetForm() {
      Object.assign(this.formData, {
        id: '',
        name: '',
        code: ''
      })
      if (this.$refs.accountTypeFormRef) {
        this.$refs.accountTypeFormRef.resetFields()
      }
    },
    handleCloseDialog() {
      if (!this.submitLoading) {
        this.dialogVisible = false
      }
    },
    async submitForm() {
      try {
        this.submitLoading = true
        await this.$refs.accountTypeFormRef.validate()

        let apiResult = null;
        if (this.isEdit) {
          apiResult = await this.fundUiAction.updateSelfFundAccountType(
            this.formData.id, 
            this.formData.name, 
            this.formData.code, 
            Engine.profile.org.orgId
          );
        } else {
          apiResult = await this.fundUiAction.createSelfFundAccountType(
            this.formData.name, 
            this.formData.code, 
            Engine.profile.org.orgId
          );
        }

        if (apiResult.resErr == null) {
          ElMessage.success(this.isEdit ? '编辑成功' : '创建成功')
          this.dialogVisible = false;
          this.getList()
        } else {
          ElMessage.error((this.isEdit ? '更新失败' : '新增失败:') + apiResult.resErr)
        }
      } catch (error) {
        console.error('提交失败', error)
        if (error !== 'validate') {
          ElMessage.error('提交失败')
        }
      } finally {
        this.submitLoading = false
      }
    },
    async delAccountTypeRecord(id) {
      try {
        await ElMessageBox.confirm('确认删除此账户类型?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
        const res = await this.fundUiAction.deleteSelfFundAccountType(id, Engine.profile.org.orgId)
        if (res.resErr) {
          ElMessage.error('删除失败:' + res.resErr);
        } else {
          ElMessage.success('删除成功')
          this.getList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败', error)
          ElMessage.error('删除失败')
        }
      }
    },
    action(data, type) {
      if (type === 'del') {
        this.delAccountTypeRecord(data.id)
      }
    },
    resetQuery() {
      this.queryParams.page = 1
      nextTick(() => {
        this.getList()
      })
    }
  },
  mounted() {
    this.getList()
  }
}
</script>